import axios from "axios";
import type {
  AxiosInstance,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import errorCode from "./Error";
import { ElMessage } from "element-plus";

// 定义响应数据接口
interface ResponseData<T = any> {
  code: number;
  data: T;
  message: string;
}

// 创建axios实例
const request: AxiosInstance = axios.create({
  baseURL: "http://localhost:3000/api",
  timeout: 10000,
  headers: {
    "Cache-Control": "no-cache",
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    console.log("[Request]", config.url);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse<ResponseData<any>>) => {
    const { data, code, message } = response.data;
    if (code === 200 || code === 201 || code === 304) {
      return data;
    } else if (code === 401) {
      ElMessage.error(errorCode[401]);
      return Promise.reject(new Error(message));
    } else if (code === 500) {
      ElMessage.error(errorCode[500]);
      return Promise.reject(new Error(message));
    }
    return Promise.reject(new Error(message));
  },
  (error) => {
    console.error("Network Error:", error);
    return Promise.reject(error);
  }
);

// 为大屏项目提供更便捷的请求方法
export const get = <T = any>(url: string, params?: any) => {
  return request.get<any, T>(url, { params });
};

export const post = <T = any>(url: string, data?: any) => {
  return request.post<any, T>(url, data);
};

export const put = <T = any>(url: string, data?: any) => {
  return request.put<any, T>(url, data);
};

export const del = <T = any>(url: string) => {
  return request.delete<any, T>(url);
};

// 数据刷新工具 - 适用于大屏定时刷新数据
export const createDataRefresher = <T = any>(
  url: string,
  interval: number,
  callback: (data: T) => void,
  errorCallback?: (error: any) => void
) => {
  const fetchAndSchedule = () => {
    get<T>(url)
      .then((data: T) => callback(data))
      .catch(errorCallback)
      .finally(() => {
        setTimeout(fetchAndSchedule, interval);
      });
  };

  // 立即执行一次
  fetchAndSchedule();

  // 返回取消函数
  return () => {
    // 可以在这里添加取消逻辑
  };
};

export default request;
